package com.breaktian.assemble.serialcache;

import android.content.Context;

import com.breaktian.assemble.AppGlobal;
import com.breaktian.assemble.security.HashUtil;
import com.breaktian.assemble.utils.FileSizeUtil;
import com.breaktian.assemble.utils.FileUtil;

import java.io.File;
import java.io.IOException;

/**
 * Created by keke.tian on 2015/9/11.
 * TODO 还差一个自动清理的Task
 */
public class SerialCache {

    private String cacheDir;


    /**
     * 首页的cache
     * */
    public static final String KEY_PART_BANNER = "PART_BANNER";//banner



    private static class InstanceHolder{
        public static final SerialCache instance = new SerialCache();
    }

    public static SerialCache get(){
        return InstanceHolder.instance;
    }


    private SerialCache() {
        cacheDir = getSerialCacheDir();
    }

    private String getSerialCacheDir(){
        File f = AppGlobal.getContext().getDir("serial_cache", Context.MODE_PRIVATE);
        if (!f.exists()){
            f.mkdirs();
        }
        return f.getPath();
    }


    private String getHashData(String key) {
        return HashUtil.GetHashCode(key, HashUtil.HashType.MD5.toString());
    }

    /**
     * 将对象序列化缓存到本地
     *
     * @param key          用于标识要保存的缓存数据
     * @param data         要序列化保存的对象
     * @return 成功返回true，否则false
     */
    public boolean saveCacheData(String key, Object data) {
        key = getHashData(key);
        return SerialCacheManager.writeCacheData(cacheDir, key, data);
    }

    /**
     * 删除本地缓存数据
     *
     * @param key          用于标识要保存的缓存数据
     * @return 成功返回true，否则false
     */
    public boolean clearCacheData(String key) {
        key = getHashData(key);
        return SerialCacheManager.clearCacheData(cacheDir, key);
    }

    /**
     * 获取缓存数据并返反序列化
     *
     * @param key          用于标识要获取的缓存数据
     * @return 成功返回对应对象实例，否则返回null
     */
    public <T> T getCacheData(String key) {
        key = getHashData(key);

        Object obj = SerialCacheManager.readCacheData(cacheDir, key);

        if (obj == null) {
            return null;
        }

        return (T) obj;
    }

    public boolean isCacheExist(String key) {
        key = getHashData(key);
        return SerialCacheManager.isCacheDataExist(cacheDir, key);
    }

    /**
     * 清除缓存
     * */
    public boolean clearCache(){
        boolean ss = false;
        try {
            FileUtil.deleteDirectory(cacheDir);
            ss = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ss;
    }

    /**
     * 获取缓存大小自动调整单位
     * */
    public String getCacheSize(){
        return FileSizeUtil.getAutoFileOrFilesSize(cacheDir);
    }

}
